package br.ufrgs.meetapp.activities;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import br.ufrgs.meetapp.lists.BuddyListArrayAdapter;
import br.ufrgs.meetapp.models.Buddy;
import br.ufrgs.meetapp.models.User;
import br.ufrgs.meetapp.utils.UserPreferencesPersistence;
import br.ufrgs.meetapp.webservices.MFTWebServiceClient;

public class TrackOthersListActivity extends ListActivity implements OnItemClickListener, OnClickListener {
	
	private ListView buddyListView;
	private ArrayList<Buddy> buddyList;
	private ImageButton refreshButton;
	private Context context;
	private BuddyListArrayAdapter buddyArrayAdapter;
	private EditText filterText;
	private ProgressBar refreshActivityIndicator;
	/**
	 * Wait for events in the search field and then refresh the listview
	 */
	private TextWatcher filterTextWatcher = new TextWatcher() {

        public void afterTextChanged(Editable search) {
        	buddyArrayAdapter.getFilter().filter(search); //Filter from my adapter
        	buddyArrayAdapter.notifyDataSetChanged(); //Update my view
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }

    };
	
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.track_others_list_activity);
        
        context = this;

        if(TrackOthersTabActivity.buddyList != null && !TrackOthersTabActivity.buddyList.isEmpty()){
        	buddyList = TrackOthersTabActivity.buddyList;
        } else {
        	buddyList = new ArrayList<Buddy>();	
        }
        
        initializeListView();
        
        new RefreshBuddyListTask().execute();
    }

	/**
	 * Initialize all views. 
	 * Get the list view, set the adapter and the onItemClickListener.
	 */
	private void initializeListView() {
		buddyListView = getListView();
		buddyListView.setTextFilterEnabled(true);
		
		buddyArrayAdapter = new BuddyListArrayAdapter(this, R.layout.cell_buddy_list, TrackOthersTabActivity.buddyList);
		buddyArrayAdapter.notifyDataSetChanged();
		setListAdapter(buddyArrayAdapter);
					
		buddyListView.setOnItemClickListener(this);
		
		refreshButton = (ImageButton)findViewById(R.id.track_others_list_activity_refresh_button);
		refreshButton.setOnClickListener(this);
		
		filterText = (EditText)findViewById(R.id.track_others_list_activity_fiter_edittext);
		filterText.addTextChangedListener(filterTextWatcher);
		
		refreshActivityIndicator = (ProgressBar) findViewById(R.id.track_others_list_activity_activity_indicator);

	}

	/**
	 * Called to refresh the listview
	 */
	private void refreshDevices() {
		//Refresh data
		buddyArrayAdapter.refreshList(TrackOthersTabActivity.buddyList, filterText.getText().toString());
		setListAdapter(buddyArrayAdapter);
		
	}	
	
	@Override
	protected void onResume() {
		
		//Check if there is a buddy selected
		try {
			if(TrackOthersTabActivity.isBuddySelected){
				TrackOthersTabActivity.isBuddySelected = false;
				Buddy buddySelected = TrackOthersTabActivity.buddySelected;
				int index = 0;
				for(Buddy buddy : buddyList){
					if(buddy.getBuddyId() == buddySelected.getBuddyId()){
						buddyListView.setSelection(index);
						break;
					}
					index++;
				}
			}
			
		} catch (Exception exception) {

			System.out
					.println("Error in TrackOthersListActivity.onResume - trying to ");
			if (exception.getMessage() != null)
				System.out.println(exception.getMessage());
			exception.printStackTrace();
			
			new RefreshBuddyListTask().execute();
			
		}
		
		
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		TrackOthersTabActivity.buddyList = new ArrayList<Buddy>(buddyArrayAdapter.getOriginalBuddyList()) ;
		TrackOthersTabActivity.filteredIds.clear();
		
		//Check if there is a filter. if yes, put the ids in the list.
		if(filterText.getText().length() != 0){
			for (Buddy buddy : TrackOthersTabActivity.buddyList){
				TrackOthersTabActivity.filteredIds.add(buddy.getBuddyId());
			}			
		}
		
		//Dismiss Keyboard
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(filterText.getWindowToken(), 0);
		
		super.onPause();
	}
	
	/**
	 * Asynchronous task to call the Web service to update the buddies informations
	 */
	private class RefreshBuddyListTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected void onPreExecute() {
			refreshButton.setVisibility(View.INVISIBLE);
			refreshActivityIndicator.setVisibility(View.VISIBLE);
			
			super.onPreExecute();
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			MFTWebServiceClient webService = new MFTWebServiceClient();
						
			try {
				Log.i("TrackOthersListActivity", "Calling WS to Refresh BuddyList");
				User user = new User();
				
				user = LoginActivity.loggedUser;
				
				buddyList = webService.listBuddies(user);
						
			} catch (Exception e) {
				System.out.println("Error in TrackOthersListActivity.RefreshBuddyListTask.doInBackground - trying to call WS to Refresh BuddyList");

				if (e.getMessage() != null) {
					System.out.println(e.getMessage());
				}

				e.printStackTrace();
			}
			return null;
		}
		

		@Override
		protected void onPostExecute(Void result) {
						
			refreshDevices();	
			
			refreshButton.setVisibility(View.VISIBLE);
			refreshActivityIndicator.setVisibility(View.INVISIBLE);
			
			super.onPostExecute(result);
		}
	}
	
	/**
	 * Switch to Map Tab
	 */
	public void switchToMapTab(){
        TrackOthersTabActivity ParentActivity;
        ParentActivity = (TrackOthersTabActivity) this.getParent();
        ParentActivity.switchTab(TrackOthersTabActivity.TAB_MAP);
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int clickedCellNumber, long arg3) {
		TrackOthersTabActivity.isBuddySelected = true;
		TrackOthersTabActivity.buddySelected = buddyArrayAdapter.getItem(clickedCellNumber);
		switchToMapTab();
	}
	
	/**
	 * Handles the click of details button
	 * @param view
	 */
	public void buddyDetailClickHandler(View view){
		int clickedItem = buddyListView.getPositionForView(view);
		
//		Intent intent = new Intent(context, BuddyDetailActivity.class);
//		intent.putExtra("BUDDY", buddyArrayAdapter.getItem(clickedItem));
//		startActivity(intent);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.track_others_list_activity_refresh_button:
			new RefreshBuddyListTask().execute();
			break;
		default:
			break;
		}
	}
	
	/**
	 * Create the hard-button menu
	 */
	public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	MenuInflater menuInflater = getMenuInflater();
    	if(UserPreferencesPersistence.getIsOnlyTrackOthers(context)){
    		menuInflater.inflate(R.menu.menu_account_about, menu);
    	} else {
    		menuInflater.inflate(R.menu.menu_settings_account_about, menu);
    	}
    	return true;
    }
    
	/**
	 * Actions to the hard-button menu
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
		case R.id.menuSettings:
			intent = new Intent(context, SettingsActivity.class);
			break;
//		case R.id.menuAccount:
//			intent = new Intent(context, AccountActivity.class);
//			break;
		case R.id.menuAbout:
			intent = new Intent(context, AboutActivity.class);
			break;
		}

		if(intent!=null){
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		}
		
		return false;
	}
}
